﻿using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.Threading;

namespace FitAutomation.Server
{
	class FitAutomationHost
	{
		ServiceHost _serviceHost;
		FitAutomationHostService _service;

		public void StartListening()
		{
			_service = new FitAutomationHostService();
			_serviceHost = new ServiceHost(_service, new Uri(Consts.Address));

			var binding = new WSDualHttpBinding()
			{
				OpenTimeout = TimeSpan.FromSeconds(2),
				CloseTimeout = TimeSpan.FromSeconds(2),
				ReceiveTimeout = TimeSpan.FromSeconds(2),
				SendTimeout = TimeSpan.FromSeconds(2),
			};

			binding.Security.Mode = WSDualHttpSecurityMode.None;

			_serviceHost.AddServiceEndpoint(typeof(IFitAutomationHostService), binding, Consts.Address);

			var smb = _serviceHost.Description.Behaviors.Find<ServiceMetadataBehavior>() ?? new ServiceMetadataBehavior();
			smb.HttpGetEnabled = true;
			smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
			_serviceHost.Description.Behaviors.Add(smb);
			_serviceHost.AddServiceEndpoint(
				ServiceMetadataBehavior.MexContractName,
				MetadataExchangeBindings.CreateMexHttpBinding(),
				"mex"
				);

			_serviceHost.Open();
			Trace.TraceInformation("Service started");
		}

		public void Loop()
		{
			_service.Live();
			while(true)
			{
				Thread.Sleep(Consts.TimeoutForAutoCleanup);
				if (!_service.CheckAlive() && !Environment.GetCommandLineArgs().Any(x => x.Equals("forever", StringComparison.InvariantCultureIgnoreCase)))
				{
					Trace.TraceInformation("Automatic shutdown.");
					break;
				}
			}
		}

	}
}